<?php
/**
 *
 * @author ninteySeven.
 * @date 2022-12-12 17:27
 */

namespace App\Services;

use AlibabaCloud\Elasticsearch\V20170613\ValidateConnection;
use App\Enum\TravelEnum;
use App\Enum\VillagerEnum;
use App\Enum\WalletsEnum;
use App\Http\Clients\ZccmzjgyxmClient;
use App\Lib\Jwt;
use App\Models\CommunityModel;
use App\Models\UserCommunityModel;
use App\Models\VillagerUserModel;
use App\Models\WalletModel;
use App\Services\Tools\HelpService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class VillagerUserService extends BaseService
{
    public $appId = null;

    public $appKey = null;

    public function __construct()
    {
        $this->appId = env('WECHAT_APP_ID');
        $this->appKey = env('WECHAT_KEY');
    }

    /**
     * 登录-个人信息
     * @param string $phone
     * @param string $openId
     * @return mixed
     * @author ninetyseven.
     * @date 2023-03-27 23:18
     */
    public function getInfo(string $phone = '', string $openId = '')
    {
        if (!empty($openId)) {
            //微信登录
            $info = VillagerUserModel::where('open_id', $openId)->first();
            if (!$info) {
                //不存在则是外来捐款人
                $addData = [
                    'phone' => $phone,
                    'is_foreign' => VillagerEnum::FOREIGN,
                ];
                $info = VillagerUserModel::create($addData);
            }
        } else {
            $info = VillagerUserModel::where('phone', $phone)->first();
        }

        $token = Jwt::createToken($info->id);
        $info['token'] = $token;
        return $info;
    }
    public function getUserWallet($userId)
    {
        $fields = ['user_id','point'=> 'point_balance', 'digital'=>'digital_balance', 'gycx_axd', 'sxcx_coin'];
        $wallet = WalletModel::query()->where(['user_id'=>$userId, 'user_type'=>VillagerEnum::USER_VILLAGER_TYPE])->select(array_values($fields))->first();
        if( empty($wallet) )throw new \Exception("钱包不存在");
        $data = $wallet->toArray();
        foreach( $fields as $key=>$field)
        {
            if( is_string($key)){
                $data[$key] = $data[$field];
                unset($data[$field]);
            }
        }
        $userPhone = VillagerUserModel::query()->where(['id'=>$userId])->value('phone');
        $wallet->commute_axd = $data['commute_axd'] = EnterpriseCommuteService::getUserScore($userPhone);
        $wallet->save();

        return $data;
    }

    /**
     * 查询用户信息根据userId
     * @param $userId
     * @return array
     * @throws GuzzleException
     * @throws \Exception
     * @author ninteySeven.
     * @date 2022-12-12 17:31
     */
    public function getUserInfo($userId): array
    {
        $res = VillagerUserModel::query()
            ->select(['id','nick_name','avatar','phone','status','identity'])
            ->find($userId);

        if (!$res) {
            throw new \Exception("用户不存在");
        }
/*
        // 捐款方不查询社区绑定
        if ($res->identity != TravelEnum::PLATFORM_DONATION) {
            $communityId = CommonService::getCommunity()['community_id'];
        }

        //捐款方不查询社区
        if ($res->identity != TravelEnum::PLATFORM_DONATION) {
            //查询社区
            $community = CommunityModel::query()->where('id', $communityId)->first();
            if (!$community) {
                throw new \Exception("社区不存在");
            }

            $res['community_name'] = $community['community_name'];
        }
        // 村委会/居委会
        if (in_array(self::getPlatformId(), [TravelEnum::PLATFORM_VILLAGER_COMMITTEE, TravelEnum::PLATFORM_MEMBER_VILLAGER])) {
            //检查是否审核通过
            $community = UserCommunityModel::query()
                ->where('user_id', $res->id)
                ->where('community_id', $communityId)
                ->first();
            if (!$community) {
                $res['is_check_community'] = false;
                $res['status'] = 0;
            } else {
                $res['is_check_community'] = true;
                $res['status'] = $community->status;
            }
        }
*/
        $res = $res->toArray();

        // 获取用户积分 20230803 by LC
        $res['score'] = $this->_fetchUserScore( $res['id'], $res['phone'] );

        // 更新用户的基本信息20230804 by LC,减少更新频次
        if (empty($res['updated_at']) || time() - strtotime($res['updated_at']) > 3600 )
            $this->_fetchUserInfo( $res['id'], $res['phone'] );

        return $res;
    }

    /**
     * 获取用户积分 20230803 by LC
     * @param $userId
     * @param $phone
     * @return int
     * @throws GuzzleException
     * @throws Exception
     */
    private function _fetchUserScore( $userId, $phone ): int
    {
        if( empty($phone) ) return 0;
        // 查询 公益诚信积分
        $result = (new ZccmzjgyxmClient())->getUserConsume($phone);
//        Log::notice("fetch user score result=>". var_export($result,true));
        $score = $result['code'] == 200 ? $result['data']['score'] : 0;

        $scores['point_balance'] = $score;
        // 查询 通勤积分
        $scores['commute_axd'] = EnterpriseCommuteService::getUserScore($phone);

        WalletModel::updateUserScore( $userId, $scores, WalletsEnum::WALLET_USER_VILLAGER );

        return $score;
    }


    /**
     * 新增微信用户
     * @param $post
     * @return mixed
     * @author ninetyseven.
     * @date 2023-04-10 22:32
     */
    public static function addWxVillager($post)
    {
        $addData = [
            'open_id' => $post['openid'],
            'session_key' => $post['session_key'],
            'identity' => TravelEnum::PLATFORM_DONATION,
            'from'  => $post['from']
        ];

        return VillagerUserModel::create($addData);
    }


    /**
     * 保存个人信息
     * @param $post
     * @return mixed
     * @throws \Exception
     * @author ninteySeven.
     * @date 2022-12-12 17:34
     */
    public function updateUserInfo($post)
    {
        return VillagerUserModel::query()->where('id', request()->userId)->update($post);
    }
    public function updateUserPhone($post)
    {
        $userId = request()->userId;
        // 取得token
        $url = sprintf(config('wx.access_token_url'), $this->appId, $this->appKey, $post['code']);
        $data = curlGet($url);
        Log::debug('fetch token');
        Log::debug(var_export($data,true));
        if ($data['errcode'] ?? 0) {
            throw new Exception($data['errmsg']);
        }
        $accessToken = $data['access_token'];
        // 使用POST和token去换取phone
        $url = sprintf(config('wx.fetch_phone_url'), $accessToken);
        $data = curlPost($url,json_encode(['code'=>$post['code']]));
        Log::debug('fetch phone');
        Log::debug(var_export($data,true));
        if ($data['errcode'] ?? 0) {
            throw new Exception($data['errmsg']);
        }
        $purePhone = $data['phone_info']['purePhoneNumber'];
        if( VillagerUserModel::query()->where(['phone'=>$purePhone])->exists()){
            throw new Exception('变更手机号失败：此手机号已经存在。');
        }
        $updateData = ['phone'=>$purePhone];
        VillagerUserModel::query()->where('id', $userId)->update($updateData);
        return $this->getUserInfo($userId);
    }

    /**
     * 查询村民列表
     */
    public static function getVillagerList(array $params = [])
    {
        $obj = VillagerUserModel::query()
            ->leftJoin('user_community', 'user_community.user_id', '=', 'user.id')
            ->select('user.id',
                'real_name',
                'nick_name',
                'avatar',
                'id_card_photo',
                'phone',
                'identity',
                'account',
                'open_id',
                'session_key',
                'is_foreign',
                'is_settlein',
                'residential_address');
        if (!empty($params['status'])) {
            $obj->where('user.is_settlein', $params['status']);
        }
        if (!empty($params['search'])) {
            $obj->where('user.nick_name', 'like', "%{$params['search']}%");
        }
        $result = $obj->where([
            'user_community.community_id' => $params['community_id'],
        ])->groupBy('user.id')->paginate(HelpService::perPage());
        if (!$result) {
            return [];
        }
        foreach ($result->items() as $row) {
            $row['status'] = $row['is_settlein'] == 1 ? VillagerEnum::STATE_NAME[VillagerEnum::SETTLE_IN] : VillagerEnum::STATE_NAME[VillagerEnum::SETTLE_OUT];
        }
        return $result;
    }
}
